<template>
  <BasicModal
    v-bind="$attrs"
    :height="600"
    width="80%"
    @open-change="handleShow"
    @register="register"
    @ok="submit"
    @cancel="cancel"
  >
    <template #title>
      <h2 class="text-center font-bold">{{ title }}</h2>
    </template>
    <template #footer>
      <div
        v-if="
          ['schedule', 'scheduleUpdate', 'quote', 'outbound', 'inbound', 'sign'].includes(fromType)
        "
        class="w-[100%] flex items-center justify-center"
      >
        <Button type="primary" class="mr-[10px]" @click="Commit()">确定</Button>
        <Button @click="cancel()">取消</Button>
      </div>
      <div
        v-else-if="['quoteCheck', 'outboundCheck', 'inboundCheck', 'signCheck'].includes(fromType)"
        class="w-[100%] flex items-center justify-center"
      >
        <Button
          class="mr-[10px]"
          @click="
            () => {
              handleCreatePrompt();
            }
          "
        >
          退回
        </Button>
        <Button type="primary" @click="Commit()"> 复核无误 </Button>
      </div>
    </template>
    <div class="flex justify-center">
      <div class="w-[80%]">
        <Header v-if="areaList.length <= 1" :data="headerData" :fromType="fromType" />
        <AreaList v-if="fromType !== 'outboundCheck'" :data="areaList" />
        <div class="border border-solid border-black p-[10px] pb-[0] my-[20px]" v-else>
          <div class="mb-[20px] font-bold">出库仓库：{{ formData.consigneeWarehouse }}</div>
          <div class="mb-[20px] flex justify-between">
            <div>送货单号：{{ formData.shippingCode }}</div>
            <div>出库日期：{{ formData.warehouseOutTime }}</div>
            <div>运输类型：{{ VehicleModel[formData.vehicleModel] }}</div>
          </div>
          <div class="mb-[20px] flex justify-between">
            <div>提货司机：{{ formData.driverName }}</div>
            <div>身份证号：{{ formData.driverIdCard }}</div>
            <div>车牌号：{{ formData.vehicleNo }}</div>
            <div>联系电话：{{ formData.driverPhone }}</div>
          </div>
          <div class="mb-[20px] font-bold">备注：{{ formData.receiverRemark }}</div>
        </div>
        <template v-if="areaList.length <= 1">
          <div class="border border-solid border-black p-[10px] pb-[0] my-[20px]">
            <div class="font-bold">货物信息</div>
            <BasicTable class="mb-[20px]" style="height: auto" @register="registerTable" />
          </div>
        </template>

        <!-- 司机调度、变更 -->
        <Schedule
          v-if="fromType === 'schedule' || fromType === 'scheduleUpdate'"
          ref="ScheduleRef"
          :fromType="fromType"
          @on-success="onSuccess"
          @on-failed="onFailed"
        />

        <!-- 报价 -->
        <Quote
          v-if="fromType === 'quote'"
          ref="QuoteRef"
          :fromType="fromType"
          @on-success="onSuccess"
          @on-failed="onFailed"
        />

        <!-- 报价复核 -->
        <QuoteCheck
          v-if="fromType === 'quoteCheck'"
          ref="QuoteCheckRef"
          :fromType="fromType"
          @on-success="onSuccess"
          @on-failed="onFailed"
        />

        <!-- 出库 -->
        <Outbound
          v-if="fromType === 'outbound' || fromType === 'inbound'"
          ref="OutboundRef"
          :fromType="fromType"
          @on-success="onSuccess"
          @on-failed="onFailed"
        />

        <!-- 出库复核 -->
        <OutboundCheck
          v-if="fromType === 'outboundCheck' || fromType === 'inboundCheck'"
          ref="OutboundCheckRef"
          :fromType="fromType"
          @on-success="onSuccess"
          @on-failed="onFailed"
        />

        <!-- 签收 -->
        <Sign
          v-if="fromType === 'sign'"
          ref="SignRef"
          :fromType="fromType"
          @on-success="onSuccess"
          @on-failed="onFailed"
        />

        <!-- 签收复核 -->
        <SignCheck
          v-if="fromType === 'signCheck'"
          ref="SignCheckRef"
          :fromType="fromType"
          @on-success="onSuccess"
          @on-failed="onFailed"
        />
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { FlowFormTypes } from './enum';
  import { ref, defineEmits, onMounted, computed } from 'vue';
  import { message, Button } from 'ant-design-vue';
  import Header from './components/header.vue';
  import AreaList from './components/areaList.vue';
  import { AreaDetailList } from '@/components/DeliveryOrderForm/types/types';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTable, ColumnChangeParam, useTable } from '@/components/Table';
  import {
    getDeliveryReceiptDetail,
    getDeliveryDetails,
    getAreaList,
  } from '@/api/waybillManagement/index';
  import { getDate } from '@/utils/time';
  import { createPrompt } from '@/components/Prompt';

  import { VehicleModel } from '@/enums/comEnum';

  import Schedule from './components/schedule.vue';
  import Quote from './components/quote.vue';
  import QuoteCheck from './components/quoteCheck.vue';
  import Outbound from './components/outbound.vue';
  import OutboundCheck from './components/outboundCheck.vue';
  import Sign from './components/sign.vue';
  import SignCheck from './components/signCheck.vue';

  import { useUserStore } from '@/store/modules/user';
  import { useAppStoreWithOut } from '@/store/modules/app';

  const userStore = useUserStore();
  const appStore = useAppStoreWithOut();

  const getUserInfo = computed(() => {
    const { userRealname, userNickname } = userStore.getUserInfo || {};
    return { userRealname, userNickname };
  });

  const emit = defineEmits(['onSearch']);

  const title = ref('');
  const fromType = ref('');

  // 头部数据
  const headerData = ref({});

  // 运输组件
  const areaList = ref<AreaDetailList>([]);

  // 获取子组件的引用
  // 调度
  const ScheduleRef = ref();
  // 报价
  const QuoteRef = ref();
  // 报价复核
  const QuoteCheckRef = ref();
  // 出库
  const OutboundRef = ref();
  // 出库复核
  const OutboundCheckRef = ref();
  // 签收
  const SignRef = ref();
  // 签收复核
  const SignCheckRef = ref();

  const queryParams = ref({} as any);

  const formData = ref({} as any);

  const initQueryParams = () => {
    queryParams.value = {
      quoteBy: '', //报价人
      quoteTime: '', //报价时间
      quoteExpireDate: '', //报价有效期时间

      shippingOrderId: 0,
      shippingOrderIdList: [],
      fileLabel: 'schedule',

      // 司机调度、变更相关
      driverName: '',
      driverPhone: '',
      vehicleNo: '',
      driverIdCard: '',
      vehicleModel: '1',
    };
  };

  onMounted(() => {
    initQueryParams();
  });

  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    data && onDataReceive(data);
  });

  const handleShow = (open: boolean) => {
    if (open) {
      setModalProps({ loading: true, confirmLoading: true });
    }
  };

  const onDataReceive = async (data) => {
    const { record, selectLists } = data;
    console.log('🚀 ~ onDataReceive ~ record, selectLists:', record, selectLists);

    initQueryParams();

    if (record) {
      areaList.value = [
        {
          receiverAddress: record.receiverAddress,
          consigneeAddress: record.consigneeAddress,
          receiverAddressDisplay: record.receiverAddressDisplay,
          consigneeAddressDisplay: record.consigneeAddressDisplay,
          distance: record.distance,
          receiverRemark: record.receiverRemark,
          deliveryCode: record.deliveryCode,
          ownerName: record.ownerName,
          goodsWeight: record.goodsWeight,
          createTime: record.createTime,
          shippingCode: record.shippingCode,
          receiverProvince: '',
          receiverCity: '',
          receiverArea: '',
          consigneeProvince: '',
          consigneeCity: '',
          consigneeArea: '',
        },
      ];

      queryParams.value.shippingOrderId = record.id;
      queryParams.value.shippingOrderIdList = [record.id];
    } else {
      queryParams.value.shippingOrderIdList = selectLists.map((item: any) => item.id);
      queryParams.value.shippingOrderId = queryParams.value.shippingOrderIdList[0];
      areaList.value = selectLists.map((item: any) => {
        return {
          receiverAddress: item.receiverAddress,
          consigneeAddress: item.consigneeAddress,
          receiverAddressDisplay: item.receiverAddressDisplay,
          consigneeAddressDisplay: item.consigneeAddressDisplay,
          distance: item.distance,
          receiverRemark: item.receiverRemark,
          deliveryCode: item.deliveryCode,
          ownerName: item.ownerName,
          goodsWeight: item.goodsWeight,
          createTime: item.createTime,
        };
      });
    }

    // 调度、合并调度、报价、合并报价头特殊处理，后端要根据不同用户分组返回
    if (
      data.fromType == 'schedule' ||
      data.fromType == 'quote' ||
      data.fromType == 'scheduleUpdate'
    ) {
      const area = await getAreaList({
        shippingOrderIds: queryParams.value.shippingOrderIdList,
      });
      areaList.value = area;
      queryParams.value.shippingOrderIdList = area.map((item: any) => item.id);
    }

    queryParams.value.fileLabel = fromType.value = data.fromType;
    title.value = FlowFormTypes[data.fromType];

    // areaList.value = data.areaList || [];

    try {
      const res = await getDeliveryReceiptDetail({
        id: queryParams.value.shippingOrderId,
        label: 'schedule',
      });
      const deliveryOrderDetails = await getDeliveryDetails({
        id: queryParams.value.shippingOrderId,
      });
      formData.value = res;

      headerData.value = {
        quoteBy: getUserInfo.value.userRealname || getUserInfo.value.userNickname,
        quoteTime: getDate.today(new Date(), 'yyyy-MM-dd'),
        quoteExpireDate: getDate.getDateAfterDays(3, 'yyyy-MM-dd'),
        vehicleModel: VehicleModel[formData.value.vehicleModel],
      };

      areaList.value.length <= 1 && setTableData(deliveryOrderDetails || []);

      console.log('🚀 ~ onDataReceive ~ queryParams.value:', queryParams.value, res);

      switch (fromType.value) {
        case 'schedule':
          ScheduleRef.value.initFormState(queryParams);
          break;
        case 'scheduleUpdate':
          ScheduleRef.value.initFormState(queryParams);
          break;
        case 'quote':
          QuoteRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        case 'quoteCheck':
          QuoteCheckRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        case 'outbound':
          OutboundRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        case 'outboundCheck':
          OutboundCheckRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        case 'inbound':
          OutboundRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        case 'inboundCheck':
          OutboundCheckRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        case 'sign':
          SignRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        case 'signCheck':
          SignCheckRef.value.initFormState({
            ...queryParams.value,
            ...res,
          });
          break;
        default:
          break;
      }
    } catch (error) {
      console.log('🚀 ~ onDataReceive ~ error:', error);
      message.error(error.message);
    }
    setModalProps({ loading: false, confirmLoading: false });
  };

  const onSuccess = async () => {
    if (fromType.value === 'outbound' && appStore.getSystem === 'Shipper') {
      setTimeout(() => {
        setModalProps({ loading: false, confirmLoading: false });
        emit('onSearch');
        closeModal();
      }, 300);
    } else {
      setModalProps({ loading: false, confirmLoading: false });
      emit('onSearch');
      closeModal();
    }
  };

  const onFailed = async () => {
    setModalProps({ loading: false, confirmLoading: false });
  };

  const Commit = async () => {
    setModalProps({ loading: true, confirmLoading: true });
    switch (fromType.value) {
      case 'schedule':
        ScheduleRef.value.Commit();
        break;
      case 'scheduleUpdate':
        ScheduleRef.value.Commit();
        break;
      case 'quote':
        QuoteRef.value.Commit();
        break;
      case 'quoteCheck':
        QuoteCheckRef.value.Commit();
        break;
      case 'outbound':
        OutboundRef.value.Commit();
        break;
      case 'outboundCheck':
        OutboundCheckRef.value.Commit();
        break;
      case 'inbound':
        OutboundRef.value.Commit();
        break;
      case 'inboundCheck':
        OutboundCheckRef.value.Commit();
        break;
      case 'sign':
        SignRef.value.Commit();
        break;
      case 'signCheck':
        SignCheckRef.value.Commit();
        break;
      default:
        break;
    }
  };

  const handleCreatePrompt = () => {
    createPrompt({
      title: '退回原因',
      label: '',
      required: true,
      defaultValue: '',
      onOK: (rejectRemark: string) => {
        console.log('🚀 ~ handleCreatePrompt ~ rejectRemark:', rejectRemark);
        Return(rejectRemark);
      },
      inputType: 'InputTextArea',
    });
  };

  const Return = async (rejectRemark) => {
    try {
      switch (fromType.value) {
        case 'quoteCheck':
          QuoteCheckRef.value.Return(rejectRemark);
          break;
        case 'outboundCheck':
          OutboundCheckRef.value.Return(rejectRemark);
          break;
        case 'inboundCheck':
          OutboundCheckRef.value.Return(rejectRemark);
          break;
        case 'signCheck':
          SignCheckRef.value.Return(rejectRemark);
          break;
        default:
          break;
      }
      // if (pageType.value == 1) {
      //   await postOutBoundRecheck({
      //     ...queryParams.value,
      //     rejectRemark,
      //     isPass: false,
      //   });
      // } else if (pageType.value == 3) {
      //   await postSignRecheck({
      //     ...queryParams.value,
      //     rejectRemark,
      //     isPass: false,
      //   });
      // }
      // closeModal();
      // message.success('处理成功');
      // emit('onSearch');
    } catch (error) {
      message.error(error.message);
    }
  };

  function handleSummary(tableData: Recordable[]) {
    const goodsWeight = tableData.reduce((prev, next) => {
      prev += next.goodsWeight || 0;
      return prev;
    }, 0);
    return [
      {
        goodsPack: '合计：' + goodsWeight + 'KG',
      },
    ];
  }

  const [registerTable, { setTableData }] = useTable({
    canResize: false,
    pagination: false,
    // isCanResizeParent: true,
    // maxHeight: 200,
    columns: [
      {
        title: '交货计划号',
        dataIndex: 'deliveryCode',
      },
      {
        title: '牌号',
        dataIndex: 'productBrandId',
      },
      {
        title: '批次号',
        dataIndex: 'goodsBatch',
      },
      {
        title: '净重(KG)',
        dataIndex: 'goodsWeight',
      },
      {
        title: '包装规格',
        dataIndex: 'goodsPack',
      },
    ],
    showSummary: true,
    summaryFunc: handleSummary,
    onColumnsChange: (data: ColumnChangeParam[]) => {
      console.log('ColumnsChanged', data);
    },
  });

  const cancel = async () => {
    initQueryParams();
    closeModal();
  };

  const submit = async () => {
    closeModal();
  };
</script>
